#!/bin/bash
# 依赖：uuidgen jq
set -e
function print_definition {
cat << EOF
{
    "type": "function",
    "function": {
        "name": "exec_shell_cmd",
        "description": "Execute a shell command after user agrees",
        "parameters": {
            "type": "object",
            "properties":{
                "cmd":{
                    "type":"string",
                    "description": "command string"
                }
            },
            "required":["cmd"]
        }
    }
}

EOF
exit
}
function print_system {
cat << EOF
### exec_shell_cmd 工具
- 执行任意shell代码
- 执行代码前用户有权拒绝代码的运行
- 输出格式：<stdout>...</stdout><stderr>...<stderr>
- 命令执行过程中用户全程可见，所以无需告知命令的执行结果
- 执行交互式命令时用户会完成交互，程序会返回交互的所有过程和结果
EOF
exit
}
if [ $# -gt 0 ]; then
    if [ "$1" = '--help' ]; then
        print_system
    elif [ "$1" = '-h' ]; then
        print_system
    elif [ "$1" = '--usage' ]; then
        print_definition
    elif [ "$1" = '-?' ]; then
        print_definition
    fi
fi
if [ $# -eq 0 ]; then
    exit 1
fi
cmd=$(echo "$1" | jq -r '.cmd')

echo 'Agent wants to run this command:'
echo "|$cmd|"
echo -n 'do you agree? [y/N] '
read -sn1 ans
if [ "$ans" != "y" ]; then
    echo 'rejected' 1>&2
    exit
fi
echo
uuid=$(uuidgen)
stdout_path="/tmp/$uuid.stdout.tmp"
stderr_path="/tmp/$uuid.stderr.tmp"
sh -c "$cmd" | tee "$stdout_path" 2>$stderr_path
echo "<stdout>$(cat $stdout_path)</stdout><stderr>$(cat $stderr_path)</stderr>" 1>&2
rm -f "$stdout_path" "$stderr_path"
